// src/utils/request.js
// 使用 owner-b.xauat.edu.cn 作为基础 URL
const baseUrl = 'https://owner-b.xauat.edu.cn'

export const request = async (url, options = {}) => {
  // 确保URL格式正确
  const fullUrl = url.startsWith('/huayun-ai') ? baseUrl + url : baseUrl + '/huayun-ai' + url

  const defaultOptions = {
    method: 'POST', // 默认使用POST方法
    headers: {
      'Content-Type': 'application/json',
      // 添加必要的请求头
      'Accept': 'application/json, text/plain, */*',
      'Referer': 'https://owner-b.xauat.edu.cn/',
      'Origin': 'https://owner-b.xauat.edu.cn',
      // 添加空的Authorization头部
      'Authorization': ''
    },
    credentials: 'include' // 确保携带cookie
  }

  const mergedOptions = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers
    }
  }

  // 如果有 token，添加到请求头
  const token = localStorage.getItem('accessToken')
  if (token) {
    mergedOptions.headers.Authorization = `Bearer ${token}`
  }

  // 如果有body且是对象，自动序列化为JSON字符串
  if (mergedOptions.body && typeof mergedOptions.body === 'object' && !(mergedOptions.body instanceof FormData)) {
    mergedOptions.body = JSON.stringify(mergedOptions.body)
  }

  try {
    const response = await fetch(fullUrl, mergedOptions)

    if (!response.ok) {
      // 处理认证失败
      if (response.status === 401 || response.status === 403) {
        // 只清除token，不重定向
        localStorage.removeItem('accessToken');
        throw new Error('AUTH_EXPIRED');
      } else if (response.status === 406) {
        // 只清除token，不重定向
        localStorage.removeItem('accessToken');
        throw new Error('PERMISSION_DENIED');
      } else {
        // 尝试解析错误响应
        let errorMsg = `HTTP error! status: ${response.status}`;
        try {
          const errorData = await response.json();
          errorMsg = errorData.msg || errorMsg;
        } catch (e) {
          // 解析失败则使用默认错误信息
        }

        throw new Error(errorMsg);
      }
    }

    return await response.json()
  } catch (error) {
    console.error('Request failed:', error)
    throw error
  }
}
